//
//  Product_Basket_Total.m
//  iFlower
//
//  Created by khanh nguyen on 7/23/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "Product_Basket_Total.h"
#import "Product_Checkout1View.h"
#import "Product.h"
#import "Basket.h"
#import "iFlowerAppDelegate.h"
#import "MyAccountView.h"
#import "LoginView.h"
#import "RegisterView.h"

@implementation Product_Basket_Total

@synthesize _table;
@synthesize _BuynowCell;
@synthesize topPriceLabel=topPriceLabel_;
@synthesize greenPriceLabel=greenPriceLabel_;
@synthesize btnRegister;
@synthesize numberItemLabel = numberItemLabel_;
@synthesize lblTitle = _lblTitle;
@synthesize titleText = _titleText;

- (void)updateBasket
{
	topPriceLabel_.text = [NSString stringWithFormat:@"%3.2f", [[[iFlowerAppDelegate shareDelegate] basket] getBasketPrice]];
	greenPriceLabel_.text = [NSString stringWithFormat:@"£%3.2f", [[[iFlowerAppDelegate shareDelegate] basket] getBasketPrice]];
	numberItemLabel_.text = [NSString stringWithFormat:@"%d", [[[iFlowerAppDelegate shareDelegate] basket] count]];	
}
-(IBAction)refreshBasket:(id)sender
{
	NSInteger num = [tableData_ count];
	for (NSInteger i=0; i<num; i++) {
		UITableViewCell* cell = [self._table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
		UITextField * quanlity = (UITextField *)[cell viewWithTag:100];
		Product* p = [tableData_ objectAtIndex:i];
		p.amount = [quanlity.text intValue];
	}
	[self updateBasket];
}
-(IBAction)buttonBack:(id)sender
{
	[self.navigationController popViewControllerAnimated:YES];
}
-(IBAction)buttonMenu:(id)sender
{
	[self.navigationController popToRootViewControllerAnimated:YES];
}
-(IBAction) buttonMyAccount
{
	if ([[iFlowerAppDelegate shareDelegate] logined]) {
		MyAccountView * account = [[MyAccountView alloc] initWithNibName:@"MyAccountView" bundle:nil];
		[self.navigationController pushViewController:account animated:YES];
		[account release];
	}
	else {
		LoginView * login = [[LoginView alloc] initWithNibName:@"LoginView" bundle:nil];
		[self.navigationController pushViewController:login animated:YES];
		[login release];		
	}
	
}
-(IBAction) buttonRegister
{
	RegisterView * registerView = [[RegisterView alloc] initWithNibName:@"RegisterView" bundle:nil];
	[self.navigationController pushViewController:registerView animated:YES];
	[registerView release];
}

-(IBAction)buttonContinue:(id)sender
{
	[self.navigationController popToRootViewControllerAnimated:YES];
}

-(IBAction)button_Checkout:(id)sender
{
	Product_Checkout1View * check1 = [[Product_Checkout1View alloc]initWithNibName:@"Product_Checkout1View" bundle:nil];
	[self.navigationController pushViewController:check1 animated:YES];
	[check1 release];
}
-(void)deleteMe:(id)sender
{
	UIButton* b = (UIButton*)sender;
	UITableViewCell* c = (UITableViewCell*)[[b superview]superview];
	NSIndexPath* indexPath = [self._table indexPathForCell:c];
	Product* p = (Product*)[tableData_ objectAtIndex:indexPath.row];
	[[[iFlowerAppDelegate shareDelegate] basket] removeFromBasket:p];
	tableData_ =[[[iFlowerAppDelegate shareDelegate] basket] products];
	[self._table reloadData];
	[self updateBasket];
}

#pragma mark Table view methods

//£
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [tableData_ count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *CellIdentifier = @"Cell";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		[[NSBundle mainBundle] loadNibNamed:@"BuynowCell" owner:self options:nil];
		cell = _BuynowCell;
		self._BuynowCell = nil;
	}
	//ClickAppDelegate* delegate = (ClickAppDelegate*) [[UIApplication sharedApplication] delegate];
	
	//UIImageView * image = (UIImageView*)[cell viewWithTag:1];
	UITextField * quanlity = (UITextField *)[cell viewWithTag:100];
	quanlity.delegate = self;
	UILabel * price = (UILabel *)[cell viewWithTag:101];
	UILabel * productName = (UILabel *)[cell viewWithTag:103];
	Product* p = [tableData_ objectAtIndex:indexPath.row];
	quanlity.text = [NSString stringWithFormat:@"%d",p.amount];
	price.text = [NSString stringWithFormat:@"£%@",p.price];
	productName.text = [NSString stringWithFormat:@"%@ [%@]",p.product,p.productCode];
	UIButton * button = (UIButton *)[cell viewWithTag:102];
	[button addTarget:self action:@selector(deleteMe:) forControlEvents:UIControlEventTouchUpInside];

	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	
	//first.text = [[tableData objectAtIndex:indexPath.row] objectForKey:@"time"];
	//second.text = [[tableData objectAtIndex:indexPath.row] objectForKey:@"videoname"];
	//third.text = [[tableData objectAtIndex:indexPath.row] objectForKey:@"description"];
	//button.titleLabel.text = [NSString stringWithFormat:@"%d",indexPath.row];
	//[button addTarget:self action:@selector(buttonBuy_Now:) forControlEvents:UIControlEventTouchUpInside];
	//image.image = [images objectAtIndex:indexPath.row];
	//[button addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
	
	//image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[tableData objectAtIndex:indexPath.row]objectForKey:@"avatar"]]]];
	return cell;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source.
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */
#pragma mark -
#pragma mark View lifecycle
- (void) viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	[self updateBasket];
	if([[iFlowerAppDelegate shareDelegate] logined])
	{
		self.btnRegister.enabled = NO;
	}else {
		self.btnRegister.enabled = YES;
	}
	tableData_ = [[[iFlowerAppDelegate shareDelegate] basket] products];
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardDidShow:) 
													 name:UIKeyboardDidShowNotification 
												   object:nil];		
	} else {
		[[NSNotificationCenter defaultCenter] addObserver:self 
												 selector:@selector(keyboardWillShow:) 
													 name:UIKeyboardWillShowNotification 
												   object:nil];
	}
}
- (void)viewWillDisappear:(BOOL)animated
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[super viewWillDisappear:animated];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	_lblTitle.text = _titleText;
	self._table.rowHeight = 90;
	_table.backgroundColor = [UIColor clearColor];
	// add observer for the respective notifications (depending on the os version)
}
- (void)addButtonToKeyboard {
	// create custom button
	UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
	doneButton.frame = CGRectMake(0, 163, 106, 53);
	doneButton.adjustsImageWhenHighlighted = NO;
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.0) {
		[doneButton setImage:[UIImage imageNamed:@"DoneUp3.png"] forState:UIControlStateNormal];
		[doneButton setImage:[UIImage imageNamed:@"DoneDown3.png"] forState:UIControlStateHighlighted];
	} else {        
		[doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
		[doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
	}
	[doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
	// locate keyboard view
	UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
	UIView* keyboard;
	for(int i=0; i<[tempWindow.subviews count]; i++) {
		keyboard = [tempWindow.subviews objectAtIndex:i];
		// keyboard found, add the button
		if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
			if([[keyboard description] hasPrefix:@"<UIPeripheralHost"] == YES)
				[keyboard addSubview:doneButton];
		} else {
			if([[keyboard description] hasPrefix:@"<UIKeyboard"] == YES)
				[keyboard addSubview:doneButton];
		}
	}
}

- (void)keyboardWillShow:(NSNotification *)note {
	// if clause is just an additional precaution, you could also dismiss it
	if ([[[UIDevice currentDevice] systemVersion] floatValue] < 3.2) {
		[self addButtonToKeyboard];
	}
}

- (void)keyboardDidShow:(NSNotification *)note {
	// if clause is just an additional precaution, you could also dismiss it
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
		[self addButtonToKeyboard];
    }
}


- (void)textFieldDidBeginEditing:(UITextField *)textField;
{
    editingField = textField;
}

- (void)doneButton:(id)sender {
	NSLog(@"doneButton");
   // NSLog(@"Input: %@", textField.text);
    [editingField resignFirstResponder];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	self.btnRegister = nil;
}


- (void)dealloc {
	[_titleText release];
	[_lblTitle release];
	[topPriceLabel_ release];
	[greenPriceLabel_ release];
	[btnRegister release];
	[_table release];
	[_BuynowCell release];
    [super dealloc];
}


@end
